var models = require('../models');
var Promise = require('bluebird');
var utils = require('../utils');
var fs = require('fs');
var util = require('util');
var multiparty = require('multiparty');
var moment = require('moment')
var path = require('path');
var consts = require('../consts');


/**
 * Created by banzhenyu on 2016/10/18.
 * 用户上传新版本相关逻辑
 */
var functions = {

    /**
     * 创建一个新应用
     * @param req apk文件
     * @param res
     * @param next
     */
    createApplication (req, res, next) {

        Promise.resolve().then(function () {

            var form = new multiparty.Form();
            form.uploadDir = consts.APKS_PATH;

            form.parse(req, function (err, fields, files) {
                if (err || files.apk == undefined) {
                    var message = (files.apk == undefined) ? "请选择安装包!" : err.message;
                    res.json({code: 1, message: `上传错误: ${message }`});
                } else {

                    //文件对象
                    let apk = files.apk[0];
                    let filePath = apk.path;

                    if (path.extname(filePath).toLocaleLowerCase() != '.apk') {
                        fs.unlink(filePath, function (err) {
                            if (!err) {
                                res.json({code: 1, message: `错误的文件类型:[ ${path.extname(filePath)} ]`});
                            }
                        });
                    } else {

                        utils.apkutils.getApplicationInfo(filePath).then(function (appInfo) {

                            var condition = {package_name: appInfo.package_name};
                            models.mysql.AppDatas.findOne({where: condition}).then(function (appData) {
                                if (appData) {
                                    fs.unlink(filePath, function (err) {
                                        if (!err) {
                                            res.json({code: 1,message: `<${appInfo.app_name}>已存在,不能重复提交,你可以尝试去更新<${appInfo.app_name}>!`});
                                        }
                                    });
                                } else {

                                    //文件重命名
                                    var apkName = appInfo.package_name
                                        + "_"
                                        + appInfo.channel_id
                                        + "_v" + appInfo.version_name
                                        + ".apk";

                                    var lastIndex = filePath.lastIndexOf("/") + 1;
                                    var newPath = filePath.substring(0, lastIndex) + apkName;
                                    fs.rename(filePath, newPath, function (err) {
                                        if (err) {
                                            console.log("重命名失败！");
                                        } else {
                                            console.log("重命名成功！");
                                            var time = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
                                            var appData = {
                                                app_name: appInfo.app_name,
                                                package_name: appInfo.package_name,
                                                created_at: time,
                                                updated_at: time
                                            };
                                            var appDetail = {
                                                app_name: appInfo.app_name,
                                                package_name: appInfo.package_name,
                                                version_code: appInfo.version_code,
                                                version_name: appInfo.version_name,
                                                update_info: '第一次发布版本!',
                                                channel_id: appInfo.channel_id,
                                                apk_size: fs.statSync(newPath).size,
                                                download_url: consts.REMOTE_SERVICE_IP + ":" + consts.REMOTE_SERVICE_PORT + "/apks/" + apkName,
                                                isforce: 0
                                            };
                                            //插入数据库
                                            models.mysql.AppDatas.create(appData);
                                            models.mysql.AppDetails.create(appDetail);
                                            res.json({code: 0, data: appData});
                                        }
                                    });
                                }
                            });
                        }).catch(function (ex) {
                            fs.unlink(filePath, function (err) {
                                if (!err) {
                                    res.json({code: 1, message: `解析安装文件失败: ${ex.message}`});
                                }
                            });
                        });
                    }
                }
            });
        }).catch(function (ex) {
            res.json({code: 1, message: ex.message});
        });
    },

    /**
     * 获取所有应用
     * @param req
     * @param res
     * @param next
     */
    getApplications (req, res, next) {
        functions.insertAccessHead(res);
        models.mysql.AppDatas.findAll().then(function (array) {
            res.json({code: 0, data: array});
        }).catch(function (ex) {
            res.json({code: 1, message: ex.message});
        });
    },

    /**
     * 删除应用
     * @param req
     * @param res
     * @param next
     */
    deleteApplication (req, res, next) {
        var condition = {package_name: req.query.package_name};
        models.mysql.AppDatas.destroy({'where': condition}).then(function (v) {
            models.mysql.AppDetails.findAll({where: condition}).then(function (versionDetail) {

                //先删文件
                for (let detail of versionDetail) {
                    var url = detail.download_url;
                    functions.deleteChannelApk(url.substring(url.lastIndexOf("/"), url.length));
                }

                //后删数据库
                models.mysql.AppDetails.destroy({'where': condition}).then(function (count) {
                    console.log("delete successfull: " + count);
                }).catch(function (ex) {
                    console.log("delete fail: " + ex)
                });
            });

            res.json({code: 0, message: "删除成功!"});
        }).catch(function (ex) {
            res.json({code: 1, message: ex.message});
        });
    },

    /**
     * 更新的渠道包
     * @param req 包名,渠道id,更新信息
     * @param res
     * @param next
     */
    uploadVersion (req, res, next) {

        Promise.resolve().then(function () {

            var form = new multiparty.Form();
            form.uploadDir = consts.APKS_PATH;

            form.parse(req, function (err, fields, files) {

                if (err || files.apk == undefined) {
                    var message = (files.apk == undefined) ? "请选择安装包!" : err.message;
                    res.json({code: 1, message: `上传错误: ${message }`});
                } else {

                    //文件对象
                    let apk = files.apk[0];
                    let filePath = apk.path;

                    if (path.extname(filePath).toLocaleLowerCase() != '.apk') {
                        fs.unlink(filePath, function (err) {
                            if (!err) {
                                res.json({code: 1, message: `错误的文件类型: [ ${path.extname(filePath)} ]`});
                            }
                        });
                    } else {

                        utils.apkutils.getApplicationInfo(filePath).then(function (appInfo) {

                            //非空判断
                            if (fields.channel_id == undefined) {
                                fields.channel_id = [appInfo.channel_id];
                            }

                            //非空判断
                            if (fields.update_info == undefined) {
                                fields.update_info = ["暂无"];
                            }

                            //文件重命名
                            var apkName = appInfo.package_name
                                + "_"
                                + appInfo.channel_id
                                + "_v" + appInfo.version_name
                                + ".apk";

                            var lastIndex = filePath.lastIndexOf("/") + 1;
                            var newPath = filePath.substring(0, lastIndex) + apkName;

                            fs.rename(filePath, newPath, function (err) {
                                if (err) {
                                    console.log("重命名失败！");
                                } else {
                                    console.log("重命名成功！");

                                    if (fields.channel_id[0] == appInfo.channel_id) {
                                        //查找有没有该渠道包
                                        var condition = {
                                            package_name: appInfo.package_name,
                                            channel_id: appInfo.channel_id
                                        };
                                        models.mysql.AppDetails.findOne({where: condition}).then(function (details) {
                                            var currentTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
                                            //准备新渠道包
                                            var appDetail = {
                                                app_name: appInfo.app_name,
                                                package_name: appInfo.package_name,
                                                version_code: appInfo.version_code,
                                                version_name: appInfo.version_name,
                                                update_info: fields.update_info[0],
                                                channel_id: appInfo.channel_id,
                                                apk_size: fs.statSync(newPath).size,
                                                updated_at: currentTime,
                                                download_url: consts.REMOTE_SERVICE_IP + ":" + consts.REMOTE_SERVICE_PORT + "/apks/" + apkName,
                                                isforce: 0
                                            };
                                            if (details) { //更新老渠道包
                                                if (appInfo.version_code > details.version_code) { //上传的版本号应该比数据库中的版本号更新,否则就是错误的操作
                                                    models.mysql.AppDetails.update(appDetail, {
                                                        where: {
                                                            package_name: appInfo.package_name,
                                                            channel_id: appInfo.channel_id
                                                        }
                                                    }).then(function (count) {
                                                        if (count > 0) {
                                                            console.log("update successfull!")
                                                        } else {
                                                            console.log("update fail!")
                                                        }
                                                    });
                                                    res.json({code: 0, data: appDetail}); //返回数据
                                                } else {
                                                    res.json({
                                                        code: 1,
                                                        message: `上传的安装包不是新版本,上传(${appInfo.version_code}) VS 服务器(${details.version_code})!`
                                                    });
                                                }
                                                functions.deleteChannelApk(apkName); //删除渠道文件
                                            } else {
                                                appDetail.created_at = currentTime;
                                                models.mysql.AppDetails.create(appDetail);
                                                res.json({code: 0, data: appDetail}); //返回数据
                                            }
                                        });
                                    } else {
                                        functions.deleteChannelApk(apkName); //删除渠道文件
                                        res.json({
                                            code: 1,
                                            message: `渠道信息不一致,(${fields.channel_id[0]}) VS (${appInfo.channel_id})!`
                                        });
                                    }
                                }
                            });


                        }).catch(function (ex) {
                            fs.unlink(filePath, function (err) {
                                if (!err) {
                                    res.json({code: 1, message: `解析安装文件失败: ${ex.message}`});
                                }
                            });
                        });
                    }
                }
            });
        }).catch(function (ex) {
            res.json({code: 1, message: ex.message});
        });
    },

    /**
     * 删除渠道包
     * @param req
     * @param res
     * @param next
     */
    deleteVersion (req, res, next) {
        var condition = {package_name: req.query.package_name, channel_id: req.query.channel_id};
        models.mysql.AppDetails.findOne({where: condition}).then(function (versionDetail) {
            if (versionDetail) {
                models.mysql.AppDetails.destroy({'where': condition}).then(function (deleteCount) {
                    if (deleteCount > 0) {

                        var url = versionDetail.download_url;
                        functions.deleteChannelApk(url.substring(url.lastIndexOf("/"), url.length));

                        //所有的渠道包都删了,需要删除appdatas表
                        var c = {package_name: req.query.package_name};
                        models.mysql.AppDetails.findAll({where: c}).then(function (d) {
                            if (d) {
                                if (d.length == 0) {
                                    var c2 = {package_name: req.query.package_name};
                                    models.mysql.AppDatas.destroy({'where': c2}).then(function (count) {
                                    }).catch(function (ex) {
                                        console.error(ex);
                                    });
                                }
                            }
                        });
                        res.json({code: 0, message: "删除成功!"});
                    }
                }).catch(function (ex) {
                    res.json({code: 1, message: ex.message});
                });
            } else {
                res.json({code: 1, message: "没有该渠道的安新包信息!"});
            }
        });

    },

    /**
     * 获取渠道包对应的版本信息
     * @param req 包名,渠道id
     * @param res
     * @param next
     */
    getVersion (req, res, next) {
        var condition = {package_name: req.query.package_name, channel_id: req.query.channel_id};
        console.log(condition.package_name + "/" + condition.channel_id)
        models.mysql.AppDetails.findOne({where: condition}).then(function (versionDetail) {
            if (versionDetail) {
                res.json({code: 0, data: versionDetail});
            } else {
                res.json({code: 1, message: "没有该渠道的安新包信息!"});
            }
        });
    },

    /**
     * 获取所有渠道包
     * @param req 包名,渠道id
     * @param res
     * @param next
     */
    getAllVersion (req, res, next) {
        var condition = {package_name: req.query.package_name};
        models.mysql.AppDetails.findAll({where: condition}).then(function (versionDetails) {
            if (versionDetails) {
                res.json({code: 0, data: versionDetails});
            } else {
                res.json({code: 1, message: "没有渠道包!"});
            }
        });
    },

    /**
     * 跨域
     */
    insertAccessHead: function (res) {
        res.header("Content-Type", "application/json");
        res.header("Access-Control-Allow-Origin", "*");
    },

    /**
     * 功能函数 删除渠道包对应的文件
     * @param details VersionDetails
     */
    deleteChannelApk: function (apkName) {
        var apkPath = consts.APKS_PATH + apkName;
        console.log("start delete file: " + apkPath);
        if (fs.existsSync(apkPath)) {
            fs.unlink(apkPath, function (err) {
                if (err) {
                    console.log("delete file fail !" + apkPath);
                    console.error(err)
                } else {
                    console.log("delete file successfull!");
                }
            });
        }
    }
};

module.exports = functions;
